package api

import (
	"strconv"

	"github.com/gin-gonic/gin"

	bookApp "BookStack/internal/application/book"
	"BookStack/internal/interfaces/middleware"
	"BookStack/internal/interfaces/presenter"
)

// BookChapterHandler 书籍章节API处理器
type BookChapterHandler struct {
	bookService bookApp.ApplicationService
	response    presenter.ResponseFormatter
}

// NewBookChapterHandler 创建书籍章节API处理器
func NewBookChapterHandler(bookService bookApp.ApplicationService) *BookChapterHandler {
	return &BookChapterHandler{
		bookService: bookService,
		response:    presenter.NewResponseFormatter(),
	}
}

// RegisterRoutes 注册书籍章节相关路由
func (h *BookChapterHandler) RegisterRoutes(r *gin.RouterGroup) {
	// 公开API
	public := r.Group("/book/:slug")
	{
		public.GET("/chapter/list", h.ListChapters)
		public.GET("/chapter/:id", h.GetChapterByID)
		public.GET("/chapter/:id/prev", h.GetPrevChapter)
		public.GET("/chapter/:id/next", h.GetNextChapter)
		public.GET("/book/:slug/chapter/search", h.SearchChapters)
	}

	// 管理员API
	admin := r.Group("/admin/book")
	admin.Use(middleware.JWTAuth(), middleware.AdminAuth()) // 管理员权限认证中间件
	{
		admin.POST("/:slug/chapter", h.CreateChapter)
		admin.PUT("/chapter/:id", h.UpdateChapter)
		admin.DELETE("/chapter/:id", h.DeleteChapter)
		admin.POST("/chapter/reorder", h.ReorderChapters)
	}
}

// ListChapters 获取书籍的章节列表
func (h *BookChapterHandler) ListChapters(c *gin.Context) {
	slug := c.Param("slug")
	if slug == "" {
		c.Error(bookApp.ValidationError("slug", "无效的书籍slug"))
		return
	}

	// 先通过slug获取书籍
	book, err := h.bookService.GetBookBySlug(c, slug)
	if err != nil {
		c.Error(err)
		return
	}

	chapters, err := h.bookService.ListChaptersByBookID(c, book.ID)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, chapters)
}

// GetChapterByID 获取章节详情
func (h *BookChapterHandler) GetChapterByID(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的章节ID"))
		return
	}

	chapter, err := h.bookService.GetChapterByID(c, uint(id))
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, chapter)
}

// GetPrevChapter 获取上一章节
func (h *BookChapterHandler) GetPrevChapter(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的章节ID"))
		return
	}

	chapter, err := h.bookService.GetPrevChapter(c, uint(id))
	if err != nil {
		c.Error(err)
		return
	}

	if chapter == nil {
		h.response.Success(c, nil)
		return
	}

	h.response.Success(c, chapter)
}

// GetNextChapter 获取下一章节
func (h *BookChapterHandler) GetNextChapter(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的章节ID"))
		return
	}

	chapter, err := h.bookService.GetNextChapter(c, uint(id))
	if err != nil {
		c.Error(err)
		return
	}

	if chapter == nil {
		h.response.Success(c, nil)
		return
	}

	h.response.Success(c, chapter)
}

// SearchChapters 搜索章节
func (h *BookChapterHandler) SearchChapters(c *gin.Context) {
	slug := c.Param("slug")
	if slug == "" {
		c.Error(bookApp.ValidationError("slug", "无效的书籍slug"))
		return
	}

	// 先通过slug获取书籍
	book, err := h.bookService.GetBookBySlug(c, slug)
	if err != nil {
		c.Error(err)
		return
	}

	keyword := c.Query("q")
	if keyword == "" {
		c.Error(bookApp.ValidationError("q", "搜索关键词不能为空"))
		return
	}

	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	if err != nil || pageSize < 1 || pageSize > 100 {
		pageSize = 20
	}

	chapters, total, err := h.bookService.SearchChaptersInBook(c, book.ID, keyword, page, pageSize)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, gin.H{
		"items": chapters,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// CreateChapter 创建章节
func (h *BookChapterHandler) CreateChapter(c *gin.Context) {
	slug := c.Param("slug")
	if slug == "" {
		c.Error(bookApp.ValidationError("slug", "无效的书籍slug"))
		return
	}

	// 先通过slug获取书籍
	book, err := h.bookService.GetBookBySlug(c, slug)
	if err != nil {
		c.Error(err)
		return
	}

	var req bookApp.CreateChapterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.Error(err)
		return
	}

	// 设置书籍ID
	req.BookID = book.ID
	// 从认证信息中获取当前用户ID
	req.CreatedBy = getUserIDFromContext(c)

	chapter, err := h.bookService.CreateChapter(c, &req)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Created(c, chapter)
}

// UpdateChapter 更新章节
func (h *BookChapterHandler) UpdateChapter(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的章节ID"))
		return
	}

	var req bookApp.UpdateChapterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.Error(err)
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	chapter, err := h.bookService.UpdateChapter(c, uint(id), &req, userID)
	if err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, chapter)
}

// DeleteChapter 删除章节
func (h *BookChapterHandler) DeleteChapter(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.Error(bookApp.ValidationError("id", "无效的章节ID"))
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	if err := h.bookService.DeleteChapter(c, uint(id), userID); err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, nil)
}

// ReorderChapters 调整章节顺序
func (h *BookChapterHandler) ReorderChapters(c *gin.Context) {
	var req bookApp.ChapterReorderRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.Error(err)
		return
	}

	// 从认证信息中获取当前用户ID
	userID := getUserIDFromContext(c)

	if err := h.bookService.ReorderChapters(c, &req, userID); err != nil {
		c.Error(err)
		return
	}

	h.response.Success(c, nil)
}
